import { createRouter, createWebHistory } from 'vue-router'
import { useUserStore } from '@/store/user'

const routes = [
  {
    path: '/login',
    name: 'Login',
    component: () => import('@/views/Login.vue')
  },
  {
    path: '/',
    redirect: '/dashboard',
    component: () => import('@/layout/Layout.vue'),
    children: [
      {
        path: '/dashboard',
        name: 'Dashboard',
        component: () => import('@/views/Dashboard.vue'),
        meta: { title: '工作台' }
      },
      {
        path: '/company',
        name: 'Company',
        component: () => import('@/views/company/Index.vue'),
        meta: { title: '公司管理' }
      },
      {
        path: '/task',
        name: 'Task',
        component: () => import('@/views/task/Index.vue'),
        meta: { title: '任务管理' }
      },
      {
        path: '/user',
        name: 'User',
        component: () => import('@/views/user/Index.vue'),
        meta: { title: '用户管理' }
      },
      {
        path: '/contract',
        name: 'Contract',
        component: () => import('@/views/contract/Index.vue'),
        meta: { title: '合同管理' }
      },
      {
        path: '/finance',
        name: 'Finance',
        component: () => import('@/views/finance/Index.vue'),
        meta: { title: '财务管理' }
      },
      {
        path: '/invoice',
        name: 'Invoice',
        component: () => import('@/views/invoice/Index.vue'),
        meta: { title: '发票管理' }
      }
    ]
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

router.beforeEach((to, from, next) => {
  const userStore = useUserStore()
  
  if (to.path === '/login') {
    next()
  } else {
    if (userStore.token) {
      next()
    } else {
      next('/login')
    }
  }
})

export default router